package com.finger.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.commonutil.exception.YyghException;
import com.finger.modelservice.enums.OrderStatusEnum;
import com.finger.modelservice.model.order.OrderInfo;
import com.finger.modelservice.model.user.Patient;
import com.finger.modelservice.result.Result;
import com.finger.modelservice.result.ResultCodeEnum;
import com.finger.modelservice.vo.hosp.ScheduleOrderVo;
import com.finger.modelservice.vo.msm.MsmVo;
import com.finger.modelservice.vo.order.OrderMqVo;
import com.finger.modelservice.vo.order.OrderQueryVo;
import com.finger.modelservice.vo.order.SignInfoVo;
import com.finger.orderservice.client.HospClient;
import com.finger.orderservice.client.UserClient;
import com.finger.orderservice.mapper.OrderInfoMapper;
import com.finger.orderservice.service.OrderInfoService;
import com.finger.serviceutil.helper.HttpRequestHelper;
import com.finger.serviceutil.util.MD5;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private HospClient hospClient;

    @Autowired
    private UserClient userClient;

//    @Autowired
//    private RabbitService rabbitService;


    @Override
    public String saveOrder(String scheduleId, String patientId) {

        Patient patient = userClient.getPatient(patientId);

        if(patient == null) throw new YyghException(ResultCodeEnum.PARAM_ERROR);

        ScheduleOrderVo scheduleOrderVO = hospClient.findScheduleOrderVO(scheduleId);

        if(scheduleOrderVO == null) throw new YyghException(ResultCodeEnum.PARAM_ERROR);

        //当前时间不可以预约
        if(new DateTime(scheduleOrderVO.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVO.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        if(scheduleOrderVO.getAvailableNumber() < 1) throw new YyghException(ResultCodeEnum.NUMBER_NO);

        SignInfoVo signInfoVO = hospClient.findSignInfoVO(scheduleOrderVO.getHoscode());

        if(signInfoVO == null) throw new YyghException(ResultCodeEnum.PARAM_ERROR);

        OrderInfo orderInfo = new OrderInfo();

        BeanUtils.copyProperties(scheduleOrderVO, orderInfo);

        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        this.save(orderInfo);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("patientId",patientId);
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVO.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType",patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
//        String sign = HttpRequestHelper.getSign(paramMap, signInfoVO.getSignKey());
        String sign = MD5.encrypt(signInfoVO.getSignKey());

        paramMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVO.getApiUrl()+"/order/submitOrder");

        if(result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            // 更新号源信息
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            Result updateScheduleResult = hospClient.updateSchedule(orderMqVo);

            if(updateScheduleResult.getCode() != 200){
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
//            //短信提示
//            MsmVo msmVo = new MsmVo();
//            msmVo.setPhone(orderInfo.getPatientPhone());
//            msmVo.setTemplateCode("SMS_194640721");
//            String reserveDate =
//                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
//                            + (orderInfo.getReserveTime()==0 ? "上午": "下午");
//            Map<String,Object> param = new HashMap<String,Object>(){{
//                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
//                put("amount", orderInfo.getAmount());
//                put("reserveDate", reserveDate);
//                put("name", orderInfo.getPatientName());
//                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
//            }};
//            msmVo.setParam(param);
//
//            orderMqVo.setMsmVo(msmVo);
//            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();

    }

    // 分页带条件查询订单接口
    @Override
    public IPage<OrderInfo> findOrderInfoPage(Page<OrderInfo> page, OrderQueryVo orderQueryVo) {

        QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();

        String keyword = orderQueryVo.getKeyword();
        String orderStatus = orderQueryVo.getOrderStatus();
        String timeBegin = orderQueryVo.getCreateTimeBegin();
        String timeEnd = orderQueryVo.getCreateTimeEnd();
        String reserveDate = orderQueryVo.getReserveDate();
        String outTradeNo = orderQueryVo.getOutTradeNo();
        String patientName = orderQueryVo.getPatientName();
        String patientId = orderQueryVo.getPatientId();
        String userId = orderQueryVo.getUserId();

        if(!StringUtils.isEmpty(userId)) orderInfoQueryWrapper.eq("user_id",userId);

        if(!StringUtils.isEmpty(keyword)) orderInfoQueryWrapper.like("hosname",keyword);

        if(!StringUtils.isEmpty(orderStatus)) orderInfoQueryWrapper.eq("order_status",orderStatus);

        if(!StringUtils.isEmpty(timeBegin)) orderInfoQueryWrapper.ge("gmt_create",timeBegin);

        if(!StringUtils.isEmpty(timeEnd)) orderInfoQueryWrapper.le("gmt_create",timeEnd);

        if(!StringUtils.isEmpty(reserveDate)) orderInfoQueryWrapper.eq("reserve_date",reserveDate);

        if(!StringUtils.isEmpty(outTradeNo)) orderInfoQueryWrapper.eq("out_trade_no",outTradeNo);

        if(!StringUtils.isEmpty(patientName)) orderInfoQueryWrapper.like("patient_name",patientName);

        if(!StringUtils.isEmpty(patientId)) orderInfoQueryWrapper.eq("patient_id",patientId);

        IPage<OrderInfo> result = baseMapper.selectPage(page, orderInfoQueryWrapper);

        result.getRecords().stream().forEach(orderInfo -> {
            this.packParam(orderInfo);
        });

        return result;
    }

    // 根据订单Id查询订单
    @Override
    public OrderInfo findOrderInfo(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);

        String orderStatusString = OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus());

        orderInfo.getParam().put("orderStatusString",orderStatusString);

        return orderInfo;
    }

    // 封装订单状态
    public void packParam(OrderInfo orderInfo){
        orderInfo.getParam().put("orderStatusString",
                OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
    }
}
